package com.itheima.d11_ziXiZuoYe;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        //1.
        Class<?> clazz = Class.forName("com.itheima.d11_ziXiZuoYe.Person");

        //2.
        Constructor<?> constructor =clazz.getConstructor(String.class,int.class) ;

        //3.
        Object person = constructor.newInstance("张三", 18);
        System.out.println( "通过构造方法创造的对象：" + person);

        //4.
        Method setNameMethod = clazz.getMethod("setName", String.class);

        //5.
        setNameMethod.invoke(person,"李四");
        System.out.println("通过方法对象setName调用方法：" + person);

        //6.
        Field ageField = clazz.getField("age");

        //7.
        ageField.set(person, 30);
        System.out.println("通过反射设置age后: " + person);

        //8.
        Field nameField = clazz.getDeclaredField("name");
        nameField.setAccessible(true);
        nameField.set(person, "王五");
        System.out.println("通过反射设置name后: " + person);

        //9.
        String nameValue = (String) nameField.get(person);
        int ageValue = (int) ageField.get(person);
        System.out.println("通过反射获取name: " + nameValue);
        System.out.println("通过反射获取age: " + ageValue);
    }
}
